//
//  PPMyFavouritesViewController.m
//  pickpic
//
//  Created by GaoYongyue on 16/8/27.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPMyFavouritesViewController.h"
#import "PPFoundViewController.h"
#import "PPMessageTimelineViewController.h"

#import "PPFavouritesCell.h"

#import "PPAlbumObject.h"

#import "PPUnreadMessageManager.h"

static const NSInteger kCount = 10;

@interface PPMyFavouritesViewController ()<PPFavouritesTimelineContentViewDelegate>
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSNumber *next;
@end

@implementation PPMyFavouritesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"收藏";

    _page = 1;

    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[PPFavouritesCell class] forCellReuseIdentifier:NSStringFromClass([PPFavouritesCell class])];

    [PPNetworkService fetchMyMessageListWithType:@"MyFavorite" before:nil size:10 onlyUnread:YES callback:nil];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.row];

    return [PPFavouritesCell heightForAlbum:album];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.row];

    PPFavouritesCell *favouriteCell = (PPFavouritesCell *)cell;
    favouriteCell.delegateViewController = self;
    favouriteCell.album = album;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    PPFavouritesCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PPFavouritesCell class])];

    return cell;
}

#pragma mark - Timeline

- (NSArray *)initialItems {
    NSString *cacheFilePath = [self cacheFilePath];

    NSData *data = [NSData dataWithContentsOfFile:cacheFilePath];

    if(data != nil) {
        NSArray *items = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        return items;
    } else {
        return nil;
    }
}

- (void)cacheItems:(NSArray *)items {
    NSString *cacheFilePath = [self cacheFilePath];

    [NSKeyedArchiver archiveRootObject:items toFile:cacheFilePath];
}

- (void)fetchNewItems {
    [super fetchNewItems];
    _page = 1;
    _next = nil;
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyFavouriteListWithPage:_page count:kCount callback:^(id data, NSError *error) {
        if(data) {
            [weakSelf didReceiveNewResult:data];
        } else {
            [weakSelf didReceiveNewResult:error];
        }
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyFavouriteListWithPage:_page count:kCount callback:^(id data, NSError *error) {
        if(data) {
            [weakSelf didReceiveMoreResult:data];
        } else {
            [weakSelf didReceiveMoreResult:error];
        }
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([_next integerValue] != -1) {
        _page++;
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    [[PPUnreadMessageManager sharedInstance] markSummariesAsReadForType:PPUnreadMessageSummaryTypeFavorite];

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([_next integerValue] != -1) {
        _page++;
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    for(NSDictionary *parameters in [[result validDictionary] validArrayForKey:@"albums"]) {
        PPAlbumObject *album = [PPAlbumObject albumForParameters:parameters];

        [items addObject:album];
    }

    return items;
}

#pragma mark - PPFavouritesTimelineContentViewDelegate
- (void)favouriteContentView:(PPFavouritesTimelineContentView *)contentView album:(PPAlbumObject *)albumID favouriteShipDidChanged:(NSNumber *)isFavourite {
    [self removeItem:albumID];
    [self reloadDataSource];
}

- (NSString *)cacheFilePath {
    NSString *directory = [NSString stringWithFormat:@"%@_Favorites", DGCurrentAccount.userID];
    NSString *path = [[[NSFileManager defaultManager] documentDirectory] stringByAppendingPathComponent:directory];

    return path;
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        DGAlignmentButton *button = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
        button.style = DGAlignmentButtonStyleImageTop;
        button.spacing = 10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        [button setImage:[UIImage imageNamed:@"icon-found-nothing"] forState:UIControlStateNormal];
        [button setTitle:@"去发现你感兴趣的图册吧" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        [button sizeToFit];
        [button addTarget:self action:@selector(emptyPromptButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];

        return button;
    }
}

- (void)emptyPromptButtonDidPressed {
    [MobClick event:@"145"];
    PPFoundViewController *foundViewController = [[UIStoryboard storyboardWithName:@"Found" bundle:nil] instantiateViewControllerWithIdentifier:@"PPFoundViewController"];
    [self.navigationController pushViewController:foundViewController animated:YES];

}

@end
